努力的人不一定能成功,但是成功的人,一定都曾努力。努力寫完今天這篇吧!
ok,今天來做下載API 跟 列出資料API吧
1.Service改加上
public Resource loadFileAsResource(String fileName) throws Exception {
....
...
}
找到filePath Path filePath = this.fileStoreLocation.resolve(fileName).normalize();
用resource處理url Resource resource = new UrlResource(filePath.toUri());
判斷存不存在
if(resource.exists()) {
return resource;
} else {
throw new Exception("找不到file " + fileName);
}
public class UrLResponse {
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
private String fileName="";
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
private String fileUrl="";
}
public List<UrLResponse> listUserAll(){
List<UrLResponse> rl=new ArrayList<>();
List<FileUpDownModel> fileUpDownModel= upLoadRepository.findAll();
for (FileUpDownModel ff:fileUpDownModel){
UrLResponse urLResponse=new UrLResponse();
urLResponse.setFileName(ff.getFileName());
urLResponse.setFileUrl(ff.getImgurl());
rl.add(urLResponse);
}
return rl;
}
4.Controller
下載API
載入resource
Resource resource = fileUpLoadService.loadFileAsResource(fileName);
設定content-type,必須設成application/octet-stream
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
}
if(contentType == null) {
contentType = "application/octet-stream";
}
回傳ResponseEntity跟header
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
@GetMapping("/downloadFile/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) throws Exception {
....
}
列出所有的資料API
用responseEntity回傳
@GetMapping("/searchAllFile")
public ResponseEntity<Object> downloadFile() throws Exception {
List<UrLResponse> urLResponses=new ArrayList<>();
for (UrLResponse file:fileUpLoadService.listUserAll()) {
// UrLResponse urLResponse=new UrLResponse();
// urLResponse.setFileName(file);
urLResponses.add(file);
}
return new ResponseEntity<Object>(urLResponses, HttpStatus.OK);
}
POSTMAN測試
postman下載網址
https://www.postman.com/downloads/
上傳圖片
可以看到有傳進去資料夾了
搜尋所有圖片
下載特定圖片